package de.fhffm.scs.simulator.gui.composites;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.csstudio.swt.widgets.figures.MeterFigure;
import org.csstudio.swt.xygraph.util.XYGraphMediaFactory;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.SchemeBorder;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;

import de.fhffm.scs.simulator.body.Body;
import de.fhffm.scs.simulator.data.BloodSugarLevel;
import org.eclipse.swt.widgets.Group;

public class BodyVisualisation extends Composite {

	public BodyVisualisation(Body b, Composite parent, int style) {
		super(parent, SWT.NONE);
		setLayout(new GridLayout(1, false));

		Group grpCurrentBloodsugarLevel = new Group(this, SWT.NONE);
		grpCurrentBloodsugarLevel.setText("Current Bloodsugar Level");
		grpCurrentBloodsugarLevel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		grpCurrentBloodsugarLevel.setBounds(0, 0, 78, 78);
		grpCurrentBloodsugarLevel.setLayout(new GridLayout(1, false));

		Canvas canvas = new Canvas(grpCurrentBloodsugarLevel, SWT.NONE);
		canvas.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1));
		GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
		gridData.widthHint = 300;
		canvas.setLayoutData(gridData);
		LightweightSystem lws = new LightweightSystem(canvas);
		
		addMeterFigure(lws, b);
	}

	public void addMeterFigure(LightweightSystem lws, final Body b) {
		// Create Gauge
		final MeterFigure meterFigure = new MeterFigure();

		// Init gauge
		meterFigure.setBackgroundColor(XYGraphMediaFactory.getInstance()
				.getColor(255, 255, 255));

		meterFigure.setBorder(new SchemeBorder(SchemeBorder.SCHEMES.ETCHED));
		meterFigure.setRange(30, 200);
		meterFigure.setLoLevel(BloodSugarLevel.LO.getMaximum().getLevel());
		meterFigure.setLoloLevel(0);
		meterFigure.setHiLevel(BloodSugarLevel.HI.getMinimum().getLevel());
		meterFigure.setHihiLevel(200);
		meterFigure.setMajorTickMarkStepHint(50);
		lws.setContents(meterFigure);

		// Update the gauge in another thread.
		ScheduledExecutorService scheduler = Executors
				.newScheduledThreadPool(1);
		scheduler.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				Display.getDefault().asyncExec(new Runnable() {
					@Override
					public void run() {
						meterFigure.setValue(b.getBloodSugarLevel());
					}
				});
			}
		}, 100, 100, TimeUnit.MILLISECONDS);
	}

}
